package ca.skygazer.client;

import ca.skygazer.shared.account.SgUser;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class SkyGazer implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	@SuppressWarnings("unused")
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	private final SgUserServiceAsync sgUserService = GWT.create(SgUserService.class);
		
	private static SgUser currentUser = null;
	VerticalPanel vp = new VerticalPanel();
	
	public static SgUser getCurrentUser(){
		return currentUser;
	}
	
	public void onModuleLoad() {
		
		RootPanel.get().add(vp);
		
		ServiceDefTarget endpoint = (ServiceDefTarget) sgUserService;  
        endpoint.setServiceEntryPoint("/skygazer/user");
        
		sgUserService.checkLogin(new AsyncCallback<Boolean>() {
			@Override
			public void onFailure(Throwable caught) {
			}
	
			@Override
			public void onSuccess(Boolean result) {
				if(result){
					sgUserService.getUser(new AsyncCallback<SgUser>(){

						@Override
						public void onFailure(Throwable caught) {
							message("ERROR getting user: "+caught.getLocalizedMessage());
						}

						@Override
						public void onSuccess(SgUser result) {
							currentUser=result;
							message("Hello "+currentUser.getNickname());

//							sgUserService.getLogoutUrl(GWT.getHostPageBaseURL()+"?gwt.codesvr=127.0.0.1:9997", new AsyncCallback<String>() {
							sgUserService.getLogoutUrl(GWT.getHostPageBaseURL(), new AsyncCallback<String>() {
								@Override
								public void onFailure(Throwable caught) {
									// TODO Auto-generated method stub							
								}
				
								@Override
								public void onSuccess(String result) {
									HTMLPanel panel = new HTMLPanel(result);
									panel.setStyleName(".gwt-Label");
									vp.add(panel);
								}
    						});
							
						}
						
					});
				} else {
					sgUserService.getLoginUrl(GWT.getHostPageBaseURL(), new AsyncCallback<String>() {

						@Override
						public void onFailure(Throwable caught) {
							message("ERROR: "+caught.getLocalizedMessage());
						}

						@Override
						public void onSuccess(String result) {
							HTMLPanel loginPanel = new HTMLPanel(result);
							vp.add(loginPanel);
						}			
					});
				}
			}
		});
		
		
	}
	
	private void message(String message){
		vp.add(new Label(message));
	}

}
